package bg.cinema_system.beans;

import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import bg.cinema_system.pojo.User;
import bg.cinema_system.service.UserServeice;
import bg.cinema_system.service.UserTicketsService;

@ManagedBean(name = "registration")
@RequestScoped
public class RegistrationBean {

	private String username;
	private String email;
	private String password;
	private String repeatPassword;
	private String warning;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRepeatPassword() {
		return repeatPassword;
	}

	public void setRepeatPassword(String repeatPassword) {
		this.repeatPassword = repeatPassword;
	}

	public String getWarning() {
		return warning;
	}

	public void setWarning(String warning) {
		this.warning = warning;
	}

	public void validateEmail(FacesContext context, UIComponent toValidate,
			Object value) throws ValidatorException {
		String emailStr = (String) value;
		String matchEmailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern emailPattern = Pattern.compile(matchEmailPattern);
		Matcher emailMatcher = emailPattern.matcher(emailStr);
		if (!emailMatcher.find()) {
			FacesMessage message = new FacesMessage("*Invalid email address");
			throw new ValidatorException(message);
		}
	}

	public void passwordValidator(FacesContext context, UIComponent toValidate,
			Object value) {
		UIInput passwordField = (UIInput) context.getViewRoot().findComponent(
				"registration-form:password");

		if (passwordField == null) {
			throw new IllegalArgumentException(
					String.format("Unable to find component."));
		}

		String password = (String) passwordField.getValue();
		String confirmPassword = (String) value;

		if (!(confirmPassword != null && confirmPassword.length() >= 5)) {
			FacesMessage message = new FacesMessage(
					"*Length is less than allowable minimum of '5'!");
			throw new ValidatorException(message);
		}

		if (!confirmPassword.equals(password)) {
			FacesMessage message = new FacesMessage("*Passwords do not match!");
			throw new ValidatorException(message);
		}
	}

	public String register() {
		User user = new User();
		user.setUsername(getUsername());
		user.setPassword(getPassword());
		user.setEmail(getEmail());
		boolean isUserExist = true;
		try {
			isUserExist = UserServeice.createNewUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			setWarning("Problem occurred, please try again.");
			return "registration";
		}
		if (isUserExist) {
			setWarning("User exists, change username!");
			return "registration";
		}

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);
		try {
			session.setAttribute("userId",
					UserTicketsService.getUserId(getUsername()));
			session.setAttribute("userRole", 1);
		} catch (SQLException e) {
			session.setAttribute("userId", 0);
		}

		return "user_daily_program";
	}

}
